<template>
  <el-icon :size="size" :color="color" :title="title" :icon="icon" class="icon">
    <slot>
      <svg v-if="svgIcon" :viewBox="viewBox" v-html="svgIcon"></svg>
      <component v-if="!svgIcon" :is="icon"></component>
    </slot>
  </el-icon>
</template>
<script>
function reslove(files) {
  // console.log("[批量组件解析]", files);
  let result = {};
  Object.keys(files || {}).forEach((key) => {
    let file = files[key] || {};
    let componentType = (key || "").replace("./icons/", "").replace(".js", "");
    let temp = file.default || file;
    if (!temp) {
      return console.error(
        `[组件解析异常] - [组件${key}没有导出default项] - [ 导出示例:export default '<path d="M0 0,L100 100"></path>' ]`,
        file
      );
    }
    if (result[componentType]) {
      return console.error(`[组件解析异常] - [组件${key}和其它组件重名]`, result[componentType]);
    }
    result[componentType] = temp;
  });
  return result;
}
export let icons = reslove(import.meta.globEager("./icons/*.js"));
import * as ElementPlusIcons from "@element-plus/icons-vue"; //全量集成element-plus图标(也可按需集成)

export let iconsSvg = (function name(files) {
  let result = {};
  let el = document.createElement("svg");
  for (const i in files) {
    let key = (i || "").replace("./icons/", "").replace(".svg", "");
    let file = files[i];
    el = document.createElement("svg");
    el.innerHTML = file || "";
    let svg = el.querySelector("svg") || {};
    result[key] = {
      viewBox: svg.getAttribute && svg.getAttribute("viewBox"),
      innerHTML: svg.innerHTML
    };
  }

  return result;
})(import.meta.glob("./icons/*.svg", { eager: true, as: "raw" }));
// console.log("[iconsSvg]", iconsSvg);
export const components = { ...ElementPlusIcons };
export default {
  name: "Icon",
  props: {
    //图标类型(组件名,或补充图标名)
    icon: { type: String },
    //图标标题
    title: { type: String },
    //图标大小
    size: { type: [String, Number] },
    //图标svg的fill颜色;有效值:html颜色
    color: { type: String }
  },
  components: components,
  data() {
    return { icons: icons, iconsSvg: iconsSvg };
  },
  computed: {
    svg() {
      let svg = this.iconsSvg[this.icon] || {};
      return svg;
    },
    viewBox() {
      return this.svg.viewBox || "0 0 1024 1024";
    },
    svgIcon() {
      return this.svg.innerHTML || this.icons[this.icon];
    }
  }
};
</script>
<style scoped>
.icon {
  flex-shrink: 0;
}
.icon svg {
  width: 100%;
  height: 100%;
}
</style>
